package com.betterjr.modules.sys.service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.betterjr.common.service.BaseService;
import com.betterjr.common.utils.BetterStringUtils;
import com.betterjr.modules.sys.dao.AreaInfoMapper;
import com.betterjr.modules.sys.entity.AreaInfo;

@Service
public class AreaInfoService extends BaseService<AreaInfoMapper, AreaInfo> {

    public Map<String, AreaInfo> findAreaInfo() {
        final List<AreaInfo> list = this.selectByProperty("status", "1");
        final Map<String, AreaInfo> map = new LinkedHashMap<String, AreaInfo>();
        String tmpKey;
        Map<String, AreaInfo> cityMap = null;
        Map<String, AreaInfo> subCityMap = null;
        String areaCode;
        for (final AreaInfo area : list) {
            areaCode = area.getAreaCode();
            if (areaCode.endsWith("0000")) {
                tmpKey = areaCode.substring(0, 2);
                map.put(tmpKey, area);
                cityMap = new LinkedHashMap<String, AreaInfo>();
                area.setCityMap(cityMap);
            } else if (areaCode.endsWith("00")) {
                tmpKey = areaCode.substring(0, 4);
                cityMap.put(tmpKey, area);
                subCityMap = new LinkedHashMap<String, AreaInfo>();
                area.setCityMap(subCityMap);
            } else {
                subCityMap.put(areaCode, area);
            }
        }
        return map;
    }

    /*****
     * 根据城市代码获取城市信息
     * @param anCode
     * @return
     */
    public String findAreaInfoByCode(final String anCode) {
        final AreaInfo areaInfo = this.selectByPrimaryKey(anCode);
        if (BetterStringUtils.isNotBlank(areaInfo.getRelationCode())) {
            return areaInfo.getRelationCode();
        } else {
            return areaInfo.getAreaCode();
        }
    }
}
